package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.MaterialMapper;
import com.heima.wemedia.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, WmMaterial> implements MaterialService {
    @Autowired
    public FileStorageService fileStorageService;


    /**
     * 自媒体端上传图片
     *
     * @param file
     * @return
     */
    @Override
    //默认回滚只针对runtimeException  对IO异常之类的不会回滚
    @Transactional(rollbackFor = Exception.class)
    public WmMaterial upload(MultipartFile file) {
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            //用户信息有问题
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        String path = null;
        try {
            String uuid = UUID.randomUUID().toString();
            String originalFilename = file.getOriginalFilename();
            //根据用户上传文件通过.分隔
            int i = originalFilename.lastIndexOf(".");
            String substring = originalFilename.substring(i);
            if (i > 0) {
                uuid = uuid + substring;
            }
            // 1 上传到minio
            path = fileStorageService.uploadImgFile(null, uuid, file.getInputStream());
            // 2 写入到数据库
            WmMaterial material = new WmMaterial();
            material.setCreatedTime(new Date());
            material.setUrl(path);
            material.setType((short) 0);
            material.setIsCollection((short) 0);
            material.setUserId(user.getId());
            save(material);
            return material;
        } catch (Exception e) {
            if (StringUtils.isBlank(path)) {
                //写入了minio
                fileStorageService.delete(path);
            }
            log.error("上传文件失败");
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }

    }


}
